# @Time : 2021/10/25 21:29
# @Author : Li Kunlun
# @Description : 单线程、多线程、多进程对cpu密集计算速度比较
import math
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import time

prime = [112272535095293] * 100


# 判断是否为素数(cpu计算，没有涉及io)
def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True


# 单线程
def single_thread():
    for number in prime:
        is_prime(number)


# 多线程
def multi_thread():
    with ThreadPoolExecutor() as pool:
        pool.map(is_prime, prime)


# 多进程
def multi_process():
    with ProcessPoolExecutor() as pool:
        pool.map(is_prime, prime)


if __name__ == '__main__':
    start = time.time()
    single_thread()
    end = time.time()
    print(f"single_thread cost:", end - start, "seconds")

    start = time.time()
    multi_thread()
    end = time.time()
    print(f"multi_thread cost:", end - start, "seconds")

    start = time.time()
    multi_process()
    end = time.time()
    print(f"multi_process cost:", end - start, "seconds")
    """
    程序执行结果：
        single_thread cost: 42.00479984283447 seconds
        multi_thread cost: 42.01970911026001 seconds
        multi_process cost: 9.357584953308105 seconds
    """
